package com.platform.car.app;

import com.alibaba.fastjson.JSONObject;
import com.platform.car.app.paramBody.ParamBody;
import com.platform.car.app.paramBody.ResponseAlarmInfoPlate;
import com.platform.car.model.*;
import com.platform.car.service.*;
import com.platform.car.socket.SocketUtil;
import com.platform.common.utils.UUIDFactory;
import com.platform.upms.model.UpmsPicture;
import com.platform.upms.model.json.Tip;
import com.platform.upms.model.param.ParamMap;
import com.platform.upms.service.UpmsPictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * * 停车场管理 客户端 Controller
 * @author GaoXiang
 * @version 1.0
 */


@Controller
@RequestMapping("/car/app/parking")
public class AppParkingController {

    /**
     *  根据省市区查询停车场
     *  2017-11-14 10:12:02 韩榕榕 迁移
     * @param parking (parking中携带着省、市、区)
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/parkStatus")
    @ResponseBody
    public Tip parking(Parking parking) throws Exception {
            List<Parking> parkingList = parkingService.selectByCity(parking); //根据省市区模糊查询出所在范围内的停车场
            for(Parking park : parkingList){  //循环所有的停车场
                parking.setId(park.getId());
                Long countParkTotal = parkingService.countParkTotal(parking); ////统计每个停车场中总车位
                Long countPark = parkingService.countPark(parking); //统计每个停车场内车位未预约的总个数
                Long countAutoParkTotal = parkingService.countAutoParkTotal(parking);  //统计每个停车场内只能车位的总个数
                Long countAutoPark = parkingService.countAutoPark(parking);  //统计每个停车场内只能车位且未预定的个数
                Long countOrdinaryParkTotal = parkingService.countOrdinaryParkTotal(parking);  //统计每个停车场内不带地锁的总个数
                Long countOrdinaryPark = parkingService.countOrdinaryPark(parking); //统计每个停车场内非智能车位且未预约的个数
                park.setCountParkTotal(countParkTotal);//所有车位
                park.setCountPark(countPark);//未预约车位的个数
                park.setCountAutoParkTotal(countAutoParkTotal);//智能车位未预定的个数
                park.setCountAutoPark(countAutoPark);//智能车位的个数
                park.setCountOrdinaryParkTotal(countOrdinaryParkTotal); //非智能车位的个数
                park.setCountOrdinaryPark(countOrdinaryPark);//非智能车位且未预定
            }
            return new Tip(parkingList);
    }


    /**
     * 停车场摄像头推送车牌
     * 2017-11-14 10:12:20 韩榕榕 迁移
     * @param request
     * @return
     * @throws Exception
     */

    @RequestMapping(value="/deviceCameraPush")
    @ResponseBody
    public Tip deviceCameraPush(HttpServletRequest request) throws Exception {
        ResponseAlarmInfoPlate rp =new ResponseAlarmInfoPlate();
//        Capture capture =new Capture();
        try {
            BufferedReader br = request.getReader();
            String str, wholeStr = "";
            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
//            Object paramBody = JSONObject.parse(wholeStr);
            ParamBody paramBody1 = JSONObject.parseObject(wholeStr, ParamBody.class);
            String plates=paramBody1.getAlarmInfoPlate().getResult().getPlateResult().getLicense();//抓拍到的车牌号
            String equipId=paramBody1.getAlarmInfoPlate().getSerialno();//摄像头的设备号
            Parkuse parkuse = new Parkuse(plates);//创建预约对象
//            parkuse.setNumberPlates(paramBody1.getAlarmInfoPlate().getResult().getPlateResult().getLicense());//给预约的车牌号赋值
            Camera camera = new Camera(equipId);//创建摄像头对象
           // camera.setEquip(paramBody1.getAlarmInfoPlate().getSerialno());//给摄像头对象设置设备号
            Camera ca = cameraService.findByEquip(camera); //根据设备获取摄像头的信息
            if (ca != null) {
                String status=ca.getStatus();//获取摄像头的状态(1:进门拍照，2：出门拍照)
                if (status !=null && "1".equals(status)) {   //进门拍照
                    System.out.println("-------进门拍照--------");

                    parkuse.setStatus("14");//已预约或者超时未进场
                    List<Parkuse> list = parkuseService.selectByPlate(parkuse);//车牌号已预约或者超时进场
                    if(list.size()>0){//判断是否有该车牌号的预约信息
                        Parkuse p=list.get(0);
                        if ("1".equals(p.getStatus())){//正常进场的
                            System.out.println("-------正常预约到场--------");
                            Capture capture1 = new Capture(plates, "1",new Date(),"正常预约到场用户",ca.getStatus(),equipId);
                            captureService.saveData(capture1);   //添加一条进场抓拍记录（已预约）  保存抓拍记录
                            p.setUseTime(new Date());p.setStatus("2");
                            parkuseService.update(p);//拍照进场后修改预约表里的预约状态  status：2 已使用
                            //根据预约表的车位id 查找车位并修改车位使用状态
                            Parkinglot parkinglot = parkinglotService.get(p.getParkinglotId());
                            if (parkinglot != null) {//修改车位状态：已使用（switchStatus:2）
                                parkinglot.setSwitchStatus("2");
                                parkinglotService.update(parkinglot); }
                             else{
                                return new Tip(1,"没有这个车位！");
                            }
                        } else { //正常预约未在规定时间内到场的车辆
                            System.out.println("-------正常预约却超时进场-------");
                            Capture capture1 = new Capture(plates,"1",new Date(),"正常预约超时到场用户",ca.getStatus(),equipId);
                            captureService.saveData(capture1); //添加一条进场抓拍记录（已预约）  保存抓拍记录
                            p.setStatus("2");
                            parkuseService.update(p);  //拍照进场后修改预约表里的预约状态  status：2 已使用
                            //根据预约表的车位id 查找车位并修改车位使用状态
                            Parkinglot parkinglot = parkinglotService.selectById(p.getParkinglotId());
                            if (parkinglot != null) {
                                parkinglot.setSwitchStatus("2");//车位状态  已使用
                                parkinglotService.update(parkinglot);
                            } else {
                                return new Tip(1, "没有这个车位！");
                            }
                        }
                    }else{
                        System.out.println("-------未预约进场-------");
                        Capture c = new Capture(plates, "0",new Date(),"未预约进场用户",ca.getStatus(),equipId);
                        captureService.saveData(c);
                        Parkinglot pt = new Parkinglot(ca.getParkingId(),"2","1");
                        List<Parkinglot> parkinglots=  parkinglotService.findByParkingId(pt); //假设给他一个车位，改为已使用状态，停车位总数-1
                        if(parkinglots.size()>0){
                            Parkinglot parkinglot = parkinglotService.get(parkinglots.get(0).getId());//  存一条数据到预约表里
                            if (parkinglot != null) {
                                parkinglot.setSwitchStatus("2"); //修改车位状态
                                parkinglotService.update(parkinglot);
                            }else{
                                return new Tip(1,"没有这个车位！");
                            }
                        }
                        Parkuse parkuse1 = new Parkuse(parkinglots.get(0).getId(),0,"2", plates,new Date(),new Date(),"未预订用户停车");
                        parkuseService.saveData(parkuse1);
                    }
                    //出门拍照
                } else if (ca.getStatus().equals("2")) {
                    System.out.println("-------------出门拍照-----------------");
                    parkuse.setStatus("2");
                    List<Parkuse> list2 = parkuseService.selectByPlate(parkuse); //查询状态为已使用的这个车是否存在
                    if (list2.size() > 0) {
                        Parkuse p=list2.get(0);
                        //正常预约进场并出场的用户
                        if (!p.getUserId().equals("0")) {
                            Capture capture1 = new Capture(plates,"1",new Date(),"正常预约进场并出场的用户",paramBody1.getAlarmInfoPlate().getResult().getPlateResult().getImagePath(),ca.getStatus(),equipId);
                            captureService.saveData(capture1);  //添加一条出场抓拍记录（正常预约 出门拍照）
                            //修改预约状态:已离开,status:3
                            Parkuse parkuse1 = new Parkuse();
                            parkuse1.setLeaveTime(new Date());
                            parkuse1.setStatus("3");
                            parkuse1.setId(p.getId());
                            parkuseService.update(parkuse1);
                            Parkinglot parkinglot = parkinglotService.get(p.getParkinglotId());   //修改车位状态
                            if (parkinglot != null) {
                                parkinglot.setSwitchStatus("1"); //归还车位，未预定
                                parkinglotService.update(parkinglot);
                            }
                            //生成支付订单（保存到支付表中）
                            Parking parking = parkingService.get(parkinglot.getParkingId());//停车场
                            Parkuse parkuse2 = parkuseService.get(p.getId());//预约记录
                            double[] expense = parkingpayService.computeMoney(parkuse2,parking);//计算费用
                            Parkingpay parkingpay = new Parkingpay(list2.get(0).getId(),Integer.valueOf((int)expense[0]),Integer.valueOf((int)expense[1]),expense[2],"0");
                            parkingpayService.saveData(parkingpay);
                            if (parkinglot != null) {
                                if (parkinglot.getLockId() != null && !"".equals(parkinglot.getLockId())){
                                    Lock lock = lockService.get(parkinglot.getLockId());
                                    if (lock != null) {
                                        lock.setLockIo("0");
                                        lock.setStatus("0");
                                        lockService.update(lock);
                                        SocketUtil.socketTaskMap.get(lock.getNumber()).closeLock();
                                    } else {
                                        return new Tip(2, "地锁不存在");
                                    }
                                }
                            }
                            else {
                                return new Tip(7, "停车位不存在");
                            }
                            rp.setInfo("ok");
                            rp.setIs_pay(true);
                            return new Tip( "拍照成功!",rp);
                            //没有使用App预约直接进门然后出门的
                        } else if (list2.get(0).getUserId().equals("0")) {
                            Capture capture1 = new Capture(plates, "0",new Date(),"未预约出场",paramBody1.getAlarmInfoPlate().getResult().getPlateResult().getImagePath(),ca.getStatus(),equipId);
                            captureService.saveData(capture1);
                            Parkuse pe = new Parkuse();
                            pe.setLeaveTime(new Date());
                            pe.setStatus("3");
                            pe.setId(list2.get(0).getId());
                            parkuseService.update(pe);//修改预约状态
                            Parkinglot pit = parkinglotService.selectById(list2.get(0).getParkinglotId());//修改车位状态
                            if (pit != null) {
                                pit.setSwitchStatus("1");//修改车位状态（未预定）
                                parkinglotService.updateById(pit);
                            } else {
                                return new Tip(1, "没有这个车位！", null);
                            }
                            //生成订单
                            Parking parking = parkingService.get(pit.getParkingId());//停车场
                            Parkuse parkuse2 = parkuseService.get(list2.get(0).getId());
                            double[] expense = parkingpayService.computeMoney(parkuse2,parking);
                            Parkingpay parkingpay = new Parkingpay(list2.get(0).getId(),Integer.valueOf((int)expense[0]),Integer.valueOf((int)expense[1]),expense[2],"0");
                            parkingpayService.saveData(parkingpay);
                        }
                    } else {
                        return new Tip(3, "没有预约的进门状态！");
                    }
                } else{
                    return new Tip(4,"没有这个摄像头状态！",null);
                }
            }else{
                return new Tip(5,"没有此设备信息！");
            }
            //capture.setPhoto(paramBody1.getAlarmInfoPlate().getResult().getPlateResult().getImagePath());
            return new Tip( "拍照成功!");
        }catch (Exception e){
            return new Tip(6,"拍照异常");
        }
    }

    /**
     * 停车场摄像头注册（心跳）
     * 2017/06/02 创建 景玭玭
     * @param request 摄像头发送过来的心跳信息
     */
    @RequestMapping("/deviceCameraRegister")
    public void deviceCameraRegister(HttpServletRequest request) {
        System.out.println("停车场摄像头注册（心跳）");
        ParamMap paramMap = new ParamMap(request);
        for (String s : paramMap.keySet()) {
            System.out.println(s + " : " + paramMap.get(s).toString());
        }
    }



    /**
     *  停车场摄像头推送串口触发信息
     * 2017-11-14 10:37:43 韩榕榕 迁移
     * @param request 摄像头推送
     * @param request
     */
    @RequestMapping("/deviceCameraSerial")
    public void deviceCameraSerial(HttpServletRequest request) {
        System.out.println(" 停车场摄像头推送串口触发信息");
        ParamMap paramMap = new ParamMap(request);
        for (String s : paramMap.keySet()) {
            System.out.println(s + " : " + paramMap.get(s).toString());
        }
    }

    /**
     * 停车场摄像头推送串口数据
     * 2017-11-14 10:40:51 韩榕榕 迁移
     * @param request
     */
    @RequestMapping("/deviceCameraSerialData")
    public void deviceCameraSerialData(HttpServletRequest request) {
        System.out.println(" 停车场摄像头推送串口数据");
        ParamMap paramMap = new ParamMap(request);
        for (String s : paramMap.keySet()) {
            System.out.println(s + " : " + paramMap.get(s).toString());
        }
    }


    /**
     *  根据经纬度查询停车场
     * 2017-11-14  韩榕榕 迁移
     * @param parking (中携带经度纬度 lat:纬度，lng:经度)
     * @return
     * @throws Exception
     */
    @RequestMapping(value="parkingScope")
    @ResponseBody
    public Tip parkingScope(Parking parking) throws Exception {
        List<Parking> list = parkingService.selectByScope(parking);
        if(list.size()>0){
            countOthers(list,parking);
            return new Tip(list);
        }else {
            return new Tip("附近没有停车场");
        }
    }

    /**
     * 统计不同状态、不同需求车位的个数
     * 2017-11-14 11:09:30  韩榕榕 迁移
     * @param list
     * @param parking
     */
    private void countOthers(List<Parking> list,Parking parking){
        for (Parking park:list) {
            UpmsPicture picture = upmsPictureService.get(park.getImgId());
            if(picture !=null ){ park.setImg(picture.getPicUrl());}
            parking.setId(park.getId());
            park.setCountParkTotal(parkingService.countParkTotal(parking));
            park.setCountPark(parkingService.countPark(parking));
            park.setCountAutoParkTotal(parkingService.countAutoParkTotal(parking));
            park.setCountAutoPark(parkingService.countAutoPark(parking));
            park.setCountOrdinaryParkTotal(parkingService.countOrdinaryParkTotal(parking));
            park.setCountOrdinaryPark(parkingService.countOrdinaryPark(parking));
        }
    }


    //---------------------------- property -------------------------------

    @Autowired
    private ParkingService parkingService;

    @Autowired
    private UpmsPictureService upmsPictureService;

    @Autowired
    private ParkuseService parkuseService;

    @Autowired
    private ParkinglotService parkinglotService;

    @Autowired
    private CameraService cameraService;

    @Autowired
    private CaptureService captureService;

    @Autowired
    private LockService lockService;

    @Autowired
    private ParkingpayService parkingpayService;

}
